package com.ycg.vue.modules.admin.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.ycg.vue.Entity.Dto.UserDto;
import com.ycg.vue.Entity.OperationLogEntity;
import com.ycg.vue.Entity.UserEntity;
import com.ycg.vue.Entity.Vo.UserVo;
import com.ycg.vue.Enum.LogEnum;
import com.ycg.vue.constant.Constant;
import com.ycg.vue.constant.TableNameConstant;
import com.ycg.vue.context.ThreadLocalContext;
import com.ycg.vue.modules.admin.mapper.UserManageMapper;
import com.ycg.vue.modules.admin.service.UserManageService;
import com.ycg.vue.modules.system.mapper.SystemMapper;
import com.ycg.vue.modules.user.mapper.UserMapper;
import com.ycg.vue.result.PageResult;
import com.ycg.vue.result.Result;
import com.ycg.vue.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Objects;
import java.util.Random;

/**
 * @Description
 * @Author jink
 * @Date 2024/5/21
 */
@Slf4j
@Service
public class UserManageServiceImpl implements UserManageService {

    @Resource
    private UserManageMapper userManageMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private SystemMapper systemMapper;

    @Override
    public PageResult list(UserDto userDto) {
        return PageResult.builder().total(userManageMapper.total(userDto, ThreadLocalContext.getUserId())).entityList(userManageMapper.list(userDto, ThreadLocalContext.getUserId())).build();
    }

    @Override
    public Result deleteUser(String id) {
        try {
            if (id == null || id.isEmpty()) return Result.error("id不能为空");
            UserVo user = userManageMapper.getUserById(id);
            if (user == null) return Result.error("用户不存在");
            if (user.getIdentity() == 1) return Result.error("超级管理员不能删除");
            userManageMapper.deleteUserById(id);
            systemMapper.insertLog(OperationLogEntity.builder().type(LogEnum.DELETE.getName()).operation(id+":"+user.getUsername()).success(true).build());
            return Result.ok("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            systemMapper.insertLog(OperationLogEntity.builder().type(LogEnum.DELETE.getName()).operation(id).success(false).message(e.getMessage()).build());
            return Result.error("删除失败");
        }
    }

    @Override
    public String headImg() {
        return userManageMapper.headImg(ThreadLocalContext.getUserId());
    }

    @Override
    public Result updateUser(UserEntity user) {
        if (user.getId() == null || user.getId().isEmpty()) {
            generateLog(user, null, false, Constant.ID_NULL_ERROR);
            return Result.error(Constant.ID_NULL_ERROR);
        }
        UserVo DbUser = userManageMapper.getUserById(user.getId());
        if (Objects.isNull(DbUser)) {
            generateLog(user, null, false, Constant.USER_NOT_EXIST);
            return Result.error(Constant.USER_NOT_EXIST);
        }
        userManageMapper.updateUser(user);
        generateLog(user, DbUser, true, "");
        return Result.ok(Constant.UPDATE_SUCCESS);
    }

    private void generateLog(UserEntity user, UserVo dbUser, Boolean success, String message) {
        OperationLogEntity log = OperationLogEntity.builder().type(LogEnum.UPDATE.getName()).success(success).message(message).build();
        if (success) {
            StringBuilder sb = new StringBuilder();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
            sb.append(user.getId()).append("->");
            if (user.getUsername() != null && dbUser.getUsername() != null && !user.getUsername().equals(dbUser.getUsername()))
                sb.append(TableNameConstant.USER_USERNAME).append(':').append(dbUser.getUsername()).append("-").append(user.getUsername()).append("、");
            if (user.getRealName() != null && dbUser.getRealName() != null && !user.getRealName().equals(dbUser.getRealName()))
                sb.append(TableNameConstant.USER_REAL_NAME).append(':').append(dbUser.getRealName()).append("-").append(user.getRealName()).append("、");
            if (user.getPhone() != null && dbUser.getPhone() != null && !user.getPhone().equals(dbUser.getPhone()))
                sb.append(TableNameConstant.USER_PHONE).append(':').append(dbUser.getPhone()).append("-").append(user.getPhone()).append("、");
            if (user.getSex() != null && dbUser.getSex() != null && !(user.getSex().equals(dbUser.getSex())))
                sb.append(TableNameConstant.USER_SEX).append(':').append(dbUser.getSex()).append("-").append(user.getSex()).append("、");
            if (user.getBirthday() != null && dbUser.getBirthday() != null && !formatter.format(user.getBirthday()).equals(formatter.format(dbUser.getBirthday())))
                sb.append(TableNameConstant.USER_BIRTHDAY).append(':').append(formatter.format(dbUser.getBirthday())).append("-").append(formatter.format(user.getBirthday())).append("、");
            if (user.getEmail() != null && dbUser.getEmail() != null && !user.getEmail().equals(dbUser.getEmail()))
                sb.append(TableNameConstant.USER_EMAIL).append(':').append(dbUser.getEmail()).append("-").append(user.getEmail()).append("、");
            if (user.getStatus() != null && dbUser.getStatus() != null && !user.getStatus().equals(dbUser.getStatus()))
                sb.append(TableNameConstant.USER_STATUS).append(':').append(dbUser.getStatus()).append("-").append(user.getStatus()).append("、");
            if (user.getIdentity() != null && dbUser.getIdentity() != null && !user.getIdentity().equals(dbUser.getIdentity()))
                sb.append(TableNameConstant.USER_IDENTITY).append(':').append(dbUser.getIdentity()).append("-").append(user.getIdentity()).append("、");
            if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1);
            log.setOperation(sb.toString());
            systemMapper.insertLog(log);
        } else {
            systemMapper.insertLog(log);
        }
    }

    @Override
    public void batchInsertUser(Integer num) {
        UserEntity user = new UserEntity();
        Short[] sex = {0, 1, 2};
        String[] groupId = {"e60259671b60470cb7b5694937b0e366", "e3821a987b404fd6ab4625afc86410d4", "acc77f7ed9a143d8976be57af3097a21", "d7dd1eaa1c9f4accb4657439e61ec98c", "714bc0d8bf5846478803d2441980f6cc"};
        int i = 0;
        while (i++ < num) {
            user.setId(UUIDUtils.getUUID());
            user.setUsername("test" + RandomUtil.randomNumbers(5));
            user.setRealName("test" + RandomUtil.randomNumbers(5));
            user.setPhone("13" + RandomUtil.randomNumbers(9));
            user.setSex(sex[new Random().nextInt(3)]);
            user.setBirthday(new java.util.Date());
            user.setEmail(RandomUtil.randomStringWithoutStr(10, "abcdefghijklmnopqrstuvwxyz@"));
            user.setPassword("c4ca4238a0b923820dcc509a6f75849b");
            user.setCreateBy(ThreadLocalContext.getUserId());
            user.setUpdateBy(ThreadLocalContext.getUserId());
            user.setCreateTime(new java.util.Date());
            user.setUpdateTime(new java.util.Date());
            user.setHeadImage(groupId[new Random().nextInt(5)]);
            userMapper.register(user);
        }
    }
}
